package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.article.entity.ApArticle;
import com.usian.article.entity.ApArticleContent;
import com.usian.article.entity.ApAuthor;
import com.usian.article.entity.ApCollection;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.service.IApArticleContentService;
import com.usian.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.article.service.IApAuthorService;
import com.usian.article.service.IApCollectionService;
import com.usian.behavior.client.BehaviorFeign;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.BeanHelper;
import com.usian.model.article.dtos.ArticleDto;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.media.dtos.WmNewsResultDTO;
import com.usian.user.client.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-12
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    /**
     * 保存app文章信息
     * @param wmNewsResultDTO 自媒体信息的dto接口
     * @return
     */
    @Autowired
    private IApAuthorService apAuthorService;

    @Autowired
    private IApArticleContentService iApArticleContentService;
    @Override
    public Long saveArticle(WmNewsResultDTO wmNewsResultDTO) {
        //保存文章信息
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNewsResultDTO.getTitle()); //标题
        //文章作者id
        LambdaQueryWrapper<ApAuthor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //
        lambdaQueryWrapper.eq(ApAuthor::getWmUserId,wmNewsResultDTO.getWmUserId());
        ApAuthor apAuthor = apAuthorService.getOne(lambdaQueryWrapper);
        if (apAuthor==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"该作者不存在");
        }
        apArticle.setAuthorId(apAuthor.getId()); //作者id
        apArticle.setAuthorName(apAuthor.getName());//作者名字
        apArticle.setChannelId(wmNewsResultDTO.getChannelId());//所属频道id
        apArticle.setChannelName(wmNewsResultDTO.getChannelName());//所属频道name
        apArticle.setLayout(wmNewsResultDTO.getType());//文章布局
        apArticle.setFlag(0);//文章标记
        apArticle.setImages(wmNewsResultDTO.getImages());//文章图片
        apArticle.setLabels(wmNewsResultDTO.getLabels());//文章标签
        apArticle.setCreatedTime(new Date());//创建时间
        apArticle.setPublishTime(wmNewsResultDTO.getPublishTime());//发布时间
        apArticle.setIsComment(true);//可以评论
        apArticle.setIsForward(true);//可以转发
        apArticle.setIsDelete(false);//没有下架
        apArticle.setIsDown(false);//未删除
        apArticle.setWmNewsId(wmNewsResultDTO.getId());//自媒体新闻id
        boolean b = save(apArticle);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"添加文章信息失败");
        }
        //保存文章内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNewsResultDTO.getContent());
        boolean b1 = iApArticleContentService.save(apArticleContent);
        if (!b1){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"添加文章内容失败");
        }
        return apArticle.getId();
    }

    /**
     * 修改上下架状态
     * @param map
     */
    @Override
    public void updateIsDown(Map<String, Integer> map) {
        LambdaUpdateWrapper<ApArticle> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ApArticle::getWmNewsId,map.get("wmNewsId")).set(ApArticle::getIsDown,map.get("enable")==1?true:false);
        boolean b = update(lambdaUpdateWrapper);
        if (!b){
            new LeadException(AppHttpCodeEnum.SERVER_ERROR,"修改状态失败");
        }
    }

    /**
     * 加载文章
     * @param dto
     * @param type
     * @return
     */
    @Override
    public List<ArticleDto> load(ArticleHomeDto dto, Integer type) {
        //获取size
        Integer size=dto.getSize();
        //如果size等于空 或者size等于0
        if (size==null|| size==0) {
            //赋值为10 展示十条数据
            size=10;
        }
        //第一页开始 展示十条数据
        Page page = new Page(1,size);
        //设置查询条件
        LambdaQueryWrapper<ApArticle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //如果不是空 并且不是查询所有的话 对频道查询进行封装
        if (!StringUtils.isEmpty(dto.getTag()) && !"__all__".equals(dto.getTag())){
            lambdaQueryWrapper.eq(ApArticle::getChannelId,dto.getTag());
        }
        //向上刷新是获取最新的数据为2
        //向下刷新是获取以前的数据为1
        if (type==1){
            lambdaQueryWrapper.le(ApArticle::getPublishTime,dto.getMinBehotTime());
        }else {
            lambdaQueryWrapper.ge(ApArticle::getPublishTime,dto.getMaxBehotTime());
        }
        lambdaQueryWrapper.eq(ApArticle::getIsDelete,false).eq(ApArticle::getIsDown,false).orderByDesc(ApArticle::getPublishTime);
        IPage iPage = page(page, lambdaQueryWrapper);
        if (iPage==null || CollectionUtils.isEmpty(iPage.getRecords())){
            new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        List<ArticleDto> articleDtoList = BeanHelper.copyWithCollection(iPage.getRecords(), ArticleDto.class);
        return articleDtoList;
    }

    /**
     * 查询文章数据
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> loadArticleInfo(ArticleInfoDto dto) {
        if (dto==null || dto.getArticleId()==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE,"参数不存在");
        }
        HashMap<String,Object> map = new HashMap();
        LambdaQueryWrapper<ApArticle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApArticle::getId,dto.getArticleId()).eq(ApArticle::getIsDown,false).eq(ApArticle::getIsDelete,false);
        ApArticle article = getOne(lambdaQueryWrapper);
        map.put("config",article);
        LambdaQueryWrapper<ApArticleContent> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent articleContent = iApArticleContentService.getOne(lambdaQueryWrapper1);
        map.put("content",articleContent);
        return map;
    }

    /**
     * 获取用户的文章关系
     * @param dto
     * @return
     */
    @Autowired
    private BehaviorFeign behaviorFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private IApCollectionService apCollectionService;

    @Override
    public Map<String, Boolean> loadArticleBehavior(ArticleInfoDto dto) {
        Boolean isUser=false;
        //获取登录信息
        Integer userId = UserThreadLocalUtils.getUserId();
        //获取主机码
        String equipmentId = dto.getEquipmentId();
        //进行判断
        if (userId==null && equipmentId==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"主机码和userid不能同时为空");
        }
        //判断userid
        if (userId!=null && userId!=0){
            isUser=true;
        }
        //进行远程调用
        //用户行为端
        Map<String, Boolean> map = behaviorFeign.findBehavior(userId, equipmentId, dto.getArticleId(), 0);

        //对用户的关系(远程调用)
        //查询follId
        ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
        Integer followId = apAuthor.getUserId();

        Boolean isUserFollow=false;
        if (isUser){
            Boolean boo = userFeign.findByUserIdAndFollowId(userId, followId);
            if (boo){
                isUserFollow=true;
            }else {
                isUserFollow=false;
            }
        }

        map.put("isfollow",isUserFollow);

        //对用户的收藏文章行为做判断(本地调用)
        LambdaQueryWrapper<ApCollection> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ApCollection::getType,0).eq(ApCollection::getArticleId,dto.getArticleId());
        if (isUser){
            lambdaQueryWrapper.eq(ApCollection::getApUserId,userId);
        }else {
            lambdaQueryWrapper.eq(ApCollection::getEquipmentId,equipmentId);
        }
        boolean iscollection =false;
        ApCollection apCollection = apCollectionService.getOne(lambdaQueryWrapper);
        if (apCollection!=null&&apCollection.getOperation()==1){
            iscollection=true;
        }
        map.put("iscollection",iscollection);



        return map;
    }

    /**
     * 文章分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<ArticleDto> findArticleByPage(int page, int size) {
        Page<ApArticle> ipage = new Page<>(page, size);
        QueryWrapper<ApArticle> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticle::getIsDelete,false).eq(ApArticle::getIsDown,false);
        IPage<ApArticle> apArticleIPage = this.page(ipage,queryWrapper);
        if(apArticleIPage != null && !CollectionUtils.isEmpty(apArticleIPage.getRecords())){
            List<ApArticle> records = apArticleIPage.getRecords();
            return BeanHelper.copyWithCollection(records,ArticleDto.class);
        }
        return null;
    }
}
